package com.supermap.wzhy.module.user.api;

import com.supermap.wzhy.common.annotation.MethodName;
import com.supermap.wzhy.common.annotation.RoleContext;
import com.supermap.wzhy.common.api.BaseController;
import com.supermap.wzhy.data.UserInfo;
import com.supermap.wzhy.entity.TRegioninfo;
import com.supermap.wzhy.entity.TUsers;
import com.supermap.wzhy.module.sys.service.RegionInfoService;
import com.supermap.wzhy.module.user.service.UserLoginService;
import com.supermap.wzhy.module.user.service.UserMajorService;
import com.supermap.wzhy.module.user.service.UserRolePowerService;
import com.supermap.wzhy.module.user.service.UserRoleService;
import org.codehaus.jackson.map.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一用户登录 API
 * <p>
 * 说明：<br/>
 * 服务启动时，web.xml上下文加载 （org.springframework.web.context.ContextLoaderListener）<br/>
 * 初始用户信息
 * </p>
 *
 * @author Created by W.Hao on 14-1-21.
 */
@Controller
@RequestMapping("/oAuth")
public class OAuthController extends BaseController {

    /** 用户登录server */
    @Autowired
    private UserLoginService userLoginService;


    /** 用户角色server */
    @Autowired
    private UserRoleService userRoleService;

    /** 用户角色权限关系server */
    @Autowired
    private UserRolePowerService userRolePowerService;

    /** 用户专业server */
    @Autowired
    private UserMajorService userMajorService;

    /** 行政区划信息server */
    @Autowired
    private RegionInfoService regionInfoService;


    /**
     * 用户登录验证、获取用户信息
     *
     * @param request
     * 			http请求
     * @param response
     * 			http响应
     * @param userName
     * 			用户名
     * @param password
     * 			密码
     * @return 登录后的结果
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @MethodName("用户登录")
    public @ResponseBody
    Map<String, Object> login(HttpServletRequest request,
                              HttpServletResponse response, @RequestParam String userName,
                              @RequestParam String password) {
        Map<String, Object> re = new HashMap<>();

        // 验证并获取用户信息
        TUsers user = userLoginService.checkUser(userName, password);
        if (user == null) {
            re.put("status", false);
            re.put("info", "用户名或密码不正确!");
            System.out.println(re);
            return re;
        }
        int userid = user.getUserid();
        String sessionid = request.getSession().getId();
        // 设置Session用户信息
        setSessionUser(request, user);
        re.put("status", true);
        re.put("info", "成功登录!");
        re.put("user", user);
        //记录日志
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return re;
    }

    /**
     * 注销登录用户
     *
     * @param request
     * 			http请求
     * @param response
     * 			http响应
     * @return  注销结果
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @MethodName("用户注销")
    public @ResponseBody String logout(HttpServletRequest request, HttpServletResponse response) {
        TUsers user = getSessionUser(request);
        if (user != null) {
            // removeSessionUser(request);
            // ServletContext context =
            // request.getSession().getServletContext();
            // ((Map)
            // context.getAttribute("sessions")).remove(user.getUserName());

            // sessions无效
            request.getSession().invalidate();
            RoleContext.INSTANCE.setCurrentRole(null);
        }
        return "ok";
    }

    /**
     * 判断用户是否登录
     *
     * @param request
     * 			http请求
     * @param response
     * 			http响应
     * @return 判断结果
     */
    @RequestMapping(value = "/isLogin", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> isLogin(HttpServletRequest request,
                                HttpServletResponse response) {
        Map<String, Object> re = new HashMap<>();

        // 从sesion获取当前用户
        TUsers tUsers = getSessionUser(request);
        if (tUsers != null && tUsers.getUserid() > 0) {
            re.put("status", true);
            re.put("info", "用户已登录！");
            re.put("user", tUsers);
        } else {
            re.put("status", false);
            re.put("info", "登录过期！");
        }
        return re;
    }

    /**
     * 获取当前登录用户的图库权限
     *
     * @param request
     * 			http请求
     * @return 图库权限
     */
    @RequestMapping(value = "/gallery/power", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> galleryPower(HttpServletRequest request) {
        Map<String, Object> re = new HashMap<>();

        // 从sesion获取当前用户
        TUsers tUsers = getSessionUser(request);
        if (tUsers != null && tUsers.getUserid() > 0) {
            re.put("status", true);
            re.put("info", "用户已登录！");
            UserInfo userInfo = new UserInfo(tUsers, null);

            // 用户所属行政区划编码
            String regionCode = userInfo.getUserRegion();
            TRegioninfo regioninfo = regionInfoService.getOneByCode(regionCode);
            if (null != regioninfo) {
                userInfo.setSmx(regioninfo.getSmx());
                userInfo.setSmy(regioninfo.getSmy());
            }

            // 获取当前用户所有图库权限
            List sysPowers = userRolePowerService.getPowerListByType(
                    tUsers.getUserid(), "10_sys", "u");

            re.put("user", userInfo);
            re.put("sysPowers", sysPowers);
        } else {
            re.put("status", false);
            re.put("power", "overdue");
            re.put("info", "登录过期！");
        }
        return re;

    }

    /**
     * 获取当前登录用户的图库权限的jsonp对象格式
     *
     * @param request
     * 			http请求
     * @return 图库权限（jsonp对象格式）
     */
    @RequestMapping(value = "/gallery/powerp", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject galleryPowerp(HttpServletRequest request) {
        String function = request.getParameter("callback");
        Map<String, Object> re = new HashMap<>();

        // 从sesion获取当前用户
        TUsers tUsers = getSessionUser(request);
        if (tUsers != null && tUsers.getUserid() > 0) {
            re.put("status", true);
            re.put("info", "用户已登录！");
            UserInfo userInfo = new UserInfo(tUsers, null);

            // 用户所属行政区划编码
            String regionCode = userInfo.getUserRegion();
            TRegioninfo regioninfo = regionInfoService.getOneByCode(regionCode);
            if (null != regioninfo) {
                userInfo.setSmx(regioninfo.getSmx());
                userInfo.setSmy(regioninfo.getSmy());
            }
            // 获取当前用户所有图库权限
            List sysPowers = userRolePowerService.getPowerListByType(
                    tUsers.getUserid(), "10_sys", "u");

            re.put("user", userInfo);
            re.put("sysPowers", sysPowers);
        } else {
            re.put("status", false);
            re.put("power", "overdue");
            re.put("info", "登录过期！");
        }
        return new JSONPObject(function, re);
    }

    /**
     * 测试
     *
     * @param request
     * 			http请求
     * @param response
     * 			http响应
     * @return session中的用户信息
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    public @ResponseBody
    TUsers check(HttpServletRequest request, HttpServletResponse response) {
        return getSessionUser(request);
    }

}
